import config from '@/config'
import { cache, getQueryString } from '@/utils'
import { getTokenByTicket, logout } from '@/api/global/user'

const { LOGOUT_URL, allowPages } = config

export const initLoginFun = async (location: any) => {
  console.log('initLoginFun location >>>>>>>>> ', location)
  const isAllowPage = allowPages.includes(location.pathname)
  if (!isAllowPage) {
    // 需授权页面
    const ticket = getQueryString('ticket')
    const token = cache.get(`token`)
    if (ticket) {
      await loginFun()
    } else if (!token) {
      await logoutFun()
    }
  }
}

export const loginFun = async () => {
  const ticket = getQueryString('ticket')
  if (ticket) {
    cache.set(`ticket`, ticket)
    await getTokenByTicket({ ticket })
  } else {
    await logoutFun()
  }
}

export const logoutFun = async () => {
  console.log('退出')
  cache.remove(`ticket`)
  cache.remove(`token`)

  const res = await logout()
  if (res.code === 2000) {
    const { origin, pathname } = window.location
    window.location.href = `${LOGOUT_URL}?url=${origin + pathname}`
  }
}
